/*
 * @Author: 明月下
 * @Date: 2022-07-30 17:43:07
 * @LastEditors: 明月下
 * @LastEditTime: 2023-03-08 19:52:37
 * @FilePath: \ali-yun-slimming\express\modules\slimming.js
 * @Description: 对数据库的操作
 */

const collection = require('../config/mongoDbConnection').getCollection('weight')
const { ObjectId } = require('mongodb')

exports.init = async (obj) => {
    try {
        const col = await collection()
        const result = col.insertOne(obj)
        return result
    } catch (error) {
        console.error(error)
        throw error + ' 初始化失败'
    }
}

exports.getByName = async (value) => {
    try {
        const col = await collection()
        console.log(typeof(value))
        if (!typeof(value)){
            return col.find({value}).toArray()
        }else {
            return col.find({}).toArray()
        }
    } catch (error) {
        console.error(error)
        throw error + ' 通过名字 查询失败'
    }
}

exports.addWeight = async (value,weight,date) => {
    try {
        const col = await collection()
        const result = await col.updateOne({value},{"$set":{[date]:weight}})
        console.log("addWeight:", result)
        if (result.matchedCount) {
            // 匹配成功，返回正确提示
            return {message: '匹配成功，已更新信息', data: result}
        } else {
            // 匹配失败，初始化新增人员
            const result = await col.insertOne({value},{"$set":{[date]:weight}})
            return {message: '匹配失败，已初始化人员信息并添加数据', data: result}
        }
    } catch (error) {
        console.error(error)
        throw error + ' 通过名字 添加体重失败'
    }
}